package com.nursebetty.droid.client.activity;

import org.json.JSONObject;

import com.nursebetty.droid.client.model.User;
import com.nursebetty.droid.client.util.RestClient;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SignIn extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signin);
        
        TextView signUpLink = (TextView)findViewById(R.id.signUpLink);
        signUpLink.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(SignIn.this, SignUp.class);
				startActivity(i);
				
			}
		});
        
        Button signinButton = (Button)findViewById(R.id.loginBtn);
        signinButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				EditText userName = (EditText)findViewById(R.id.emailField);
				EditText password = (EditText)findViewById(R.id.passwordField);
				
				try {
					JSONObject response = RestClient.connect("http://10.0.2.2:8080/nb/login?name=" + userName.getText().toString()
																+"&p=" + password.getText().toString());
					User u = createUserHistory(response);
					//if the login was successful then 
					//set the user object and go to main page
					if (u != null){
						Intent i = new Intent(SignIn.this, Main.class);
						i.putExtra("user", u);
						Bundle b = new Bundle();
						b.putSerializable("user", u);
						i.putExtras(b);
						
						startActivity(i);
					}else{
						//not SucessfullLogin
						TextView error = (TextView) findViewById(R.id.error);
						error.setText("There was an error in loging in");
					}

				}catch(Exception e){
					
				}
				
				
			}

			private User createUserHistory(JSONObject json) {
				try {
					User u = new User();
					int id = json.optInt("id");
                	u.setUserId(id);
	                return u;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
		});
    }
}